from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import re
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


#抢票目标页
target_url="https://www.polyt.cn/show/621299187621089280/1321/33619"


class Concert(object):
    def __init__(self):
        self.status = 0
        self.login_method = 0
        self.date = 1  #选择哪一天，按数字排列，比如2021-01-01，2021-01-02，2021-01-03可选，想选01-01填1，想选01-02填2
        self.price= 1  #买哪一档票，从贵到便宜，1，2，3
        self.total_wait_time = 5   #WebDriverWait总等待时间
        self.refresh_wait_time = 0.5 #WebDriverWait刷新动作的时间
        chrome_options = Options()
        chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")  #控制当前chrome页面
        chrome_driver = "E:/Data/02_Code/07_Ticket_Order/Automatic_ticket_purchase-master/chromedriver.exe" # 指定自己的chromedriver路径
        self.driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
        print("初始化成功，载入页面中")
    
    def isClassPresent(self, item, name, ret=False):
        try:
            result = item.find_element_by_class_name(name)
            if ret:
                return result
            else:
                return True
        except:
            return False


    def prepare(self):
        self.driver.get(target_url)
        self.driver.refresh()
        start = False
        locator = (By.XPATH, "/html/body/div/div/div/div[2]/div/div[2]/div/div[2]/div/div[1]/span")
        while not start:
            try:
                WebDriverWait(self.driver, 10,0.1).until(EC.text_to_be_present_in_element(locator,'售票中'))
                print("获取页面成功")
                break
            except Exception as e:
                print("未开始")

    def choose_ticket(self):
        choiceTime_xpath = "//*[@id=\"app\"]/div/div/div[2]/div/div[2]/div/div[2]/div/div[2]"
        selectbut_xpath  = "//*[@id=\"app\"]/div/div/div[2]/div/div[2]/div/div[2]/div/div[5]/button"

        print("="*30)
        print("###开始进行日期选择###")
        
        selectbut_xpath  = "//*[@id=\"app\"]/div/div/div[2]/div/div[2]/div/div[2]/div/div[5]/button"
        while self.driver.title.find('选择座位') == -1:           #如果跳转到了订单结算界面就算这步成功了，否则继续执行此步
            choiceTime = WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until(
                    EC.presence_of_element_located((By.XPATH, choiceTime_xpath)))
            choiceTime_list = choiceTime.find_elements_by_tag_name('span')  

            if self.date>len(choiceTime_list):
                actualDate = choiceTime_list[0]
                print("想选的日期不存在，自动选择" + actualDate)
                date_list[0].click()
            else:
                choiceTime_list[self.date-1].click()
            
            selectbut = self.driver.find_element_by_xpath(selectbut_xpath)
            selectbut.click()
            print("日期选择中")

        print("###日期选择成功###")
            
    def seatSelect(self):
        print("="*30)
        print("###开始进行座位选择###")

        
        while self.driver.title.find('确认订单') == -1: 
            while True:  #当中有耗时的查找座位表动作，用true循环查到再进下一步
                print("找可选的位置")
                try:
                    seatbuyerxpath = "//*[@id=\"frameBody\"]/div[1]"
                    seatxpath = "/html/body/div/div/div/div/div[3]/div[1]/div[2]/div/div[2]/i"
                    seat = WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until(
                        EC.presence_of_element_located((By.XPATH, seatxpath)))
                    seatbuyer = WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until(
                        EC.presence_of_element_located((By.XPATH, seatbuyerxpath)))
                    seat_list = seatbuyer.find_elements_by_class_name("iconfont")
                    botLeft_list = seatbuyer.find_elements_by_class_name("botLeft-list")
                except Exception as e:
                    print("找不到座位信息")
                    raise Exception("***错误：找不到座位信息***")
                price_color_list = []
                if len(seat_list) != 0:
                    break

            print("可选的位置已经找到")

            for botLeft in botLeft_list:
                seattype = botLeft.find_element_by_class_name('font-bold').text
                seatprice = botLeft.find_element_by_class_name('grade-price').text
                seatcolor = botLeft.find_element_by_class_name('seat-color').get_attribute('style')
                p1 = re.compile(r'[(](.*?)[)]', re.S)
                color = re.findall(p1, seatcolor)
                print('seattype:'+seattype+' seatprice:'+seatprice+' seatcolor:'+ color[0])
                price_color_list.append(color[0])
                
            print(price_color_list)
            if len(price_color_list) <= 0 :
                print("没有可选的票档，请手动选择")
                
            if self.price > len(price_color_list):
                self.price = 1
        
            for seat in seat_list:
                if price_color_list[self.price-1] in seat.get_attribute('style'):
                    seatid = seat.get_attribute('id')
                    print('seatid' + seatid)
                    button= 'document.getElementById(\"'+seatid+'\").click()'
                    print(button)
                    self.driver.execute_script(button)
                    parent = seat.find_element_by_xpath("..")
                    ActionChains(self.driver).move_to_element(parent).perform()
                    parent.click()
                    break
                else:
                    continue
            locator = (By.XPATH, "/html/body/div/div/div/div/div[3]/div[1]/div[4]")
            try:
                WebDriverWait(self.driver, 3,0.3).until_not(EC.text_to_be_present_in_element_value(locator,'botrightActive'))
                print("seat selected")
                button= 'document.getElementsByClassName("c-btn")[0].click()' # 防止页面跳转不及时或者元素未出现的情况，用js脚本的方式点击按钮
                self.driver.execute_script(button)
                print("###座位选择成功###")
                break
            except Exception as e:
                print("座位选择失败，自动重新选择")


    def checkout(self):
        print("="*30)
        print("###开始填写支付信息###")

        while self.driver.title.find('订单支付') == -1:
            audience_select_xpath = "//*[@id=\"app\"]/div/div/div/div[2]/div[3]/div[3]/div/div/button"
            audience_confirm_xpath = "//*[@id=\"app\"]/div/div/div/div[4]/div/div[3]/div/div[1]"
            pay_xpath = "/html/body/div/div/div/div/div[2]/div[4]/div[3]/div/button"
            
            try:
                audience_select = WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until(
                        EC.presence_of_element_located((By.XPATH, audience_select_xpath)))
                audience_select.click()
                
                print("###等联系人confirm###")
                audience_confirm= WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until(
                        EC.element_to_be_clickable((By.XPATH, audience_confirm_xpath)))
                # audience_confirm= WebDriverWait(self.driver, self.total_wait_time, self.refresh_wait_time).until(
                #         EC.presence_of_element_located((By.XPATH, audience_confirm_xpath)))
                audience_confirm.click()
                print("###等支付按键###")

                payment = self.driver.find_element_by_xpath(pay_xpath)
                ActionChains(self.driver).move_to_element(payment).perform()
                button= 'document.getElementsByClassName("c-btn")[0].click();'
                self.driver.execute_script(button)
                print("###支付按钮按下###")
                break
            except Exception as e:
                print("观众信息填写错误，自动重新填写")
        
        print('抢票成功，请尽快支付')


if __name__ == '__main__':
    try:
        con = Concert()             #具体如果填写请查看类中的初始化函数
        con.prepare()
        con.choose_ticket()
        con.seatSelect()
        con.checkout()

    except Exception as e:
        print(e)
        con.finish()


            

 
        
